package com.example.hospitalbakcends.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * ZXing 工具类
 */
public class QRCode {

    /** 二维码上传位置 */
    private static String codePath = "src/";
    /** 二维码宽度 */
    private static Integer width = 150;
    /** 二维码高度 */
    private static Integer height = 150;


    /**
     * 解析二维码
     *
     * @param name 文件名
     * @return 二维码内容
     * @throws IOException
     * @throws NotFoundException
     */
    public static String decode(String name) throws IOException, NotFoundException {
        String filepath = codePath + name + ".png";
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);
        HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
        decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = new MultiFormatReader().decode(bitmap, decodeHints);
        return result.getText();
    }

    /**
     * 生成二维码
     *
     * @param content 内容
     * @param name 文件名
     * @return 二维码路径
     * @throws WriterException
     * @throws IOException
     */
    public static String encode(String content, String name) throws WriterException, IOException {
        Map<EncodeHintType, Object> encodeHints = new HashMap<EncodeHintType, Object>();
        encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, encodeHints);
        String filepath = codePath + name + ".png";
        Path path = FileSystems.getDefault().getPath(filepath);
        MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
        return codePath + name + ".png";
    }

}
